import axios from 'axios'
import {Notification, MessageBox, Message, Loading} from 'element-ui'
// import sysConfig from "@/config";
// import tool from '@/utils/tool';
axios.defaults.baseURL = ''
// HTTP response 拦截器
axios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response) {
      if (error.response.status === 404) {
        Notification.error({
          title: '请求错误',
          message: 'Status:404，正在请求不存在的服务器记录！'
        })
      } else if (error.response.status === 500) {
        Notification.error({
          title: '请求错误',
          message: error.response.data.message || 'Status:500，服务器发生错误！'
        })
      } else if (error.response.status === 401) {
        MessageBox.confirm('当前用户已被登出或无权限访问当前资源，请尝试重新登录后再操作。', '无权限访问', {
          type: 'error',
          closeOnClickModal: false,
          center: true,
          confirmButtonText: '重新登录'
        }).then(() => {
          // router.replace({ path: '/login' });
        })
          .catch(() => { })
      } else {
        Notification.error({
          title: '请求错误',
          message: error.message || `Status:${error.response.status}，未知错误！`
        })
      }
    } else {
      Notification.error({
        title: '请求错误',
        message: '请求服务器无响应！'
      })
    }

    return Promise.reject(error.response)
  }
)

const http = {
  /** get 请求
   * @param  {接口地址} url
   * @param  {请求参数} params
   * @param  {参数} config
   */
  get: function (url, params = {}, config = {}) {
    return new Promise((resolve, reject) => {
      let defaultSet = {}
      if (sessionStorage.baseUser !== null) {
        defaultSet = {
          'token': sessionStorage.token,
          'udid': sessionStorage.udid,
          'user_id': sessionStorage.user_id,
          'tech_id': sessionStorage.tech_id,
          'user_name': sessionStorage.use,
          'org_id': sessionStorage.org_id,
          'version': 0
        }
      }
      axios({
        method: 'get',
        url: url,
        params: Object.assign(defaultSet, params),
        ...config
      }).then((response) => {
        resolve(response.data)
      })
        .catch((error) => {
          reject(error)
        })
    })
  },
  /** post 请求
   * @param  {接口地址} url
   * @param  {请求参数} data
   * @param  {参数} config
   */
  post: function (url, data = {}, config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }) {
    return new Promise((resolve, reject) => {
      let defaultSet = {}
      if (sessionStorage.baseUser !== undefined) {
        defaultSet = {
          'token': sessionStorage.token,
          'udid': sessionStorage.udid,
          'user_id': sessionStorage.user_id,
          'tech_id': sessionStorage.tech_id,
          'user_name': sessionStorage.use,
          'org_id': sessionStorage.org_id,
          'version': 0
        }
      }

      let newData = null
      if (data.entries) {
        newData = data
        for (const attr in defaultSet) {
          newData.append(attr, defaultSet[attr])
        }
      } else {
        const dealData = Object.assign(defaultSet, data)
        newData = new FormData()
        for (const attr in dealData) {
          newData.append(attr, dealData[attr])
        }
      }

      axios({
        method: 'post',
        url: url,
        data: newData,
        ...config
      }).then((response) => {
        resolve(response.data)
      })
        .catch((error) => {
          reject(error)
        })
    })
  },
  down: function (url, data = {}, config = {
    headers: {
      'Content-Type': 'multipart/form-data'
     }
  }, okFun) {
    return new Promise((resolve, reject) => {
      let defaultSet = {}
      if (sessionStorage.baseUser !== undefined) {
        defaultSet = {
          'token': sessionStorage.token,
          'udid': sessionStorage.udid,
          'user_id': sessionStorage.user_id,
          'tech_id': sessionStorage.tech_id,
          'user_name': sessionStorage.use,
          'org_id': sessionStorage.org_id,
          'version': 0
        }
      }

      let newData = null
      if (data.entries) {
        newData = data
        for (const attr in defaultSet) {
          newData.append(attr, defaultSet[attr])
        }
      } else {
        const dealData = Object.assign(defaultSet, data)
        newData = new FormData()
        for (const attr in dealData) {
          newData.append(attr, dealData[attr])
        }
      }

      let downloadProgress='0KB'
      const loading = Loading.service({
        lock: true,
        text: '下载:'+downloadProgress,
        spinner: 'el-icon-loading',
        customClass:'test3848'
      })

      axios({
        method: 'post',
        url: url,
        data: newData,
        responseType: 'blob', // 返回是个文件，
        onDownloadProgress: (progressEvent) => {
          // 计算下载进度
          console.log(progressEvent.loaded)
          // const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            // if (data.onDownloadProgress) {
              // data.onDownloadProgress(progress) // 调用回调函数，通过参数传递进度
              // data.onDownloadProgress=progress // 调用回调函数，通过参数传递进度
              downloadProgress=Math.round(progressEvent.loaded/1024)+'KB'
              console.log(downloadProgress)
              document.getElementsByClassName('el-loading-text')[0].innerHTML='下载:'+downloadProgress
            // }
        },
        ...config
      }).then((response) => {
        loading.close()
        // 返回的是一个错误
        if (response.headers['content-type'] === 'application/json') {
          // 提取错误的json消息并转换(此时json消息依旧在response.data中，这是一个blob数据)
          let reader = new FileReader()
          reader.onload = e => this.$message.error(JSON.parse(e.target.result).msg)
          reader.readAsText(response.data)
          return false
        }
         // 接收的是文件,fileName是一个property,设置了默认值(比如"文件模版.xls")
        let fileName = data.fileName||'文件模版.xlsx'
        // 服务器返回的请求头中包含了文件名信息,提取出来
        // 可能出现的BUG:如果在响应头中能看到"content-disposition",axios拿到的response却没有,
        // 这不怪axios，你需要去服务器设置一个叫Access-Control-Expose-Headers的东西
        // 让它包含"content-disposition"
        if (response.headers['content-disposition']) {
          const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
          const result = patt.exec(response.headers['content-disposition'])
          if (result.length > 1) {
            // 中文解码
            // fileName = decodeURIComponent(result[1])
            fileName = decodeURIComponent(fileName)
          }
        }
        // 制作a标签并点击下载
        const url = window.URL.createObjectURL(new Blob([response.data],
          { type: 'application/octet-stream' }))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', fileName)
        document.body.appendChild(link)
        link.click()
        if (okFun) {
          okFun()
        }
        Message.success({
          message: '下载成功！'
        })
      })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // 图片上传
  upload: function (url, data = {}, config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  }) {
    return new Promise((resolve, reject) => {
      let defaultSet = {}
      if (sessionStorage.baseUser !== undefined) {
        defaultSet = {
          'token': sessionStorage.token,
          'udid': sessionStorage.udid,
          'user_id': sessionStorage.user_id,
          'tech_id': sessionStorage.tech_id,
          'user_name': sessionStorage.use,
          'org_id': sessionStorage.org_id,
          'version': 0
        }
      }

      // const formData = new FormData();
      // formData.append('file', file);
      let newData = null
      if (data.entries) {
        newData = data
        for (const attr in defaultSet) {
          newData.append(attr, defaultSet[attr])
        }
      } else {
        const dealData = Object.assign(defaultSet, data)
        newData = new FormData()
        for (const attr in dealData) {
          newData.append(attr, dealData[attr])
        }
      }

      axios({
        method: 'post',
        url: url,
        data: newData,
        ...config
      }).then((response) => {
        resolve(response.data)
      })
        .catch((error) => {
          reject(error)
        })
    })
  },
  /** delete 请求
   * @param  {接口地址} url
   * @param  {请求参数} data
   * @param  {参数} config
   */
  delete: function (url, data = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'delete',
        url: url,
        data: data,
        ...config
      }).then((response) => {
        resolve(response.data)
      })
        .catch((error) => {
          reject(error)
        })
    })
  },
  /** jsonp 请求
   * @param  {接口地址} url
   * @param  {JSONP回调函数名称} name
   */
  jsonp: function (url, name = 'jsonp') {
    return new Promise((resolve) => {
      const script = document.createElement('script')
      const _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
      script.id = _id
      script.type = 'text/javascript'
      script.src = url
      window[name] = (response) => {
        resolve(response)
        document.getElementsByTagName('head')[0].removeChild(script)
        try {
          delete window[name]
        } catch (e) {
          window[name] = undefined
        }
      }
      document.getElementsByTagName('head')[0].appendChild(script)
    })
  }
}

export default http
